package com.qm.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.qm.pojo.Cart;
import com.qm.pojo.User;
import com.qm.service.DubboCartService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 @author james
 @create 2021-04-29 22:18
 */
@Controller
@RequestMapping("/cart")
public class CartController {

    //消费者启动时，不需要检查是否有服务的提供者
    @Reference(check = false)
    private DubboCartService cartService;

    @RequestMapping("/show")
    public String showCart(Model model, HttpServletRequest request) {
        User user = (User) request.getAttribute("QM_USER");
        Long userId = user.getId();
        List<Cart> cartList = cartService.findCartListByUserId(userId);
        model.addAttribute("cartList", cartList);
        return "cart";
    }

    /**
     * 业务需求:  完成购物车更新操作
     * 1.url地址: http://www.qm.com/cart/update/num/562379/13
     * 2.请求参数: 562379-itemId  /13-num
     * 3.返回值结果: void
     */
    @RequestMapping("/update/num/{itemId}/{num}")
    @ResponseBody
    public void updateCart(Cart cart, HttpServletRequest request) {
        User user = (User) request.getAttribute("QM_USER");
        Long userId = user.getId();
        cart.setUserId(userId);
        cartService.updateCartNum(cart);
    }

    /**
     * url地址:http://www.qm.com/cart/add/562379.html
     * 参数: 表单数据提交  cart
     * 返回值: 重定向到购物车展现页面
     */
    @RequestMapping("/add/{itemId}")
    public String saveCart(Cart cart, HttpServletRequest request) {
        User user = (User) request.getAttribute("QM_USER");
        Long userId = user.getId();
        cart.setUserId(userId);
        cartService.saveCart(cart);
        return "redirect:/cart/show.html";

    }

    /**
     * url地址:http://www.qm.com/cart/delete/1352516.html
     * 参数: 表单数据提交  cart
     * 返回值: 重定向到购物车展现页面
     */
    @RequestMapping("/delete/{itemId}")
    public String deleteCart(Cart cart, HttpServletRequest request) {
        User user = (User) request.getAttribute("QM_USER");
        Long userId = user.getId();
        cart.setUserId(userId);
        cart.setItemId(cart.getItemId());
        cartService.deleteCart(cart);
        return "redirect:/cart/show.html";
    }


}
